package com.atguigu.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.atguigu.exception.CustomException;
import com.atguigu.pojo.Account;
import com.atguigu.pojo.Employee;
import com.atguigu.pojo.Result;
import com.atguigu.service.AdminService;
import com.atguigu.service.ArticleService;
import com.atguigu.service.EmployeeService;
import jakarta.annotation.Resource;
import lombok.Data;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@CrossOrigin(origins = "*")
public class WebController {

    @Resource
    private EmployeeService employeeService;
    @Resource
    private AdminService adminService;
    @Resource
    private ArticleService articleService;

    @RequestMapping("hello")
    public Result hello() {
//        int a = 1/ 0;
//        手动抛出异常
        throw  new CustomException("400", "running error");
//        return Result.success("hello");
    }
    @RequestMapping("login")
    public Result login(@RequestBody Account account) {

        if("ADMIN".equals(account.getRole())) {
            return Result.success(adminService.login(account));
        } else if("EMP".equals(account.getRole())) {
            return Result.success(employeeService.login(account));
        } else {
            throw new CustomException("500", "非法状态！");
        }
    }
    @PostMapping("register")
    public Result register(@RequestBody Employee employee) {
        employeeService.register(employee);
        return Result.success();
    }
    @PutMapping("updatePassword")
    public Result updatePassword(@RequestBody Account account) {
        if("ADMIN".equals(account.getRole())) {
            adminService.updatePassword(account);
            return Result.success();
        } else if("EMP".equals(account.getRole())) {
            employeeService.updatePassword(account);
            return Result.success();
        } else {
            throw new CustomException("500", "非法状态！");
        }

    }

    @GetMapping("barData")
    public Result getBarData() {
        // 获取所有员工数据
        List<Employee> employeeList = employeeService.selectAll(null);

        // 过滤掉 departmentName 为 null 的员工，并按部门分组
        Map<String, Long> departmentCountMap = employeeList.stream()
                .filter(employee -> employee.getDepartmentName() != null)
                .collect(Collectors.groupingBy(
                        Employee::getDepartmentName,
                        Collectors.counting()
                ));

        // 提取部门名称和员工数量
        List<String> departments = new ArrayList<>(departmentCountMap.keySet());
        List<Long> employeeCounts = new ArrayList<>(departmentCountMap.values());

        // 封装结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("departments", departments); // x 轴
        resultMap.put("employeeCounts", employeeCounts); // y 轴

        return Result.success(resultMap);
    }
    @GetMapping("lineData")
    public Result getLineData() {
        // 获取所有员工数据
        Map<String, Object> resultMap = new HashMap<>();
        Date date = new Date();
        DateTime start = DateUtil.offsetDay(date, -7);
        List<DateTime> dateTimeList = DateUtil.rangeToList(start, date, DateField.DAY_OF_YEAR);
        // 把 DateTime 类型的日期转换成  字符串类型的日期  ["10月22日", "10月23日"...]
        List<String> dateStrList = dateTimeList.stream().map(dateTime -> DateUtil.format(dateTime, "MM月dd日"))
                .sorted(Comparator.naturalOrder()).collect(Collectors.toList());
        resultMap.put("date", dateStrList);  // x轴数据

        List<Integer> countList = new ArrayList<>();
        for(DateTime day : dateTimeList) {
            String dayFormat = DateUtil.formatDate(day);
            Integer count = articleService.selectCountByDate(dayFormat);
            countList.add(count);
        }
        resultMap.put("count", countList); // Y轴数据
        return Result.success(resultMap);
    }
    @GetMapping("/pieData")
    public Result getPieData() {
        List<Map<String, Object>> list = new ArrayList<>();
        List<Employee> employeeList = employeeService.selectAll(null);

        // 过滤掉 departmentName 为 null 的员工，并获取所有部门名称（去重）
        Set<String> departmentNameSet = employeeList.stream()
                .filter(employee -> employee.getDepartmentName() != null) // 过滤掉 null
                .map(Employee::getDepartmentName)
                .collect(Collectors.toSet());

        // 统计每个部门的员工数量
        for (String departmentName : departmentNameSet) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("name", departmentName);
            long count = employeeList.stream()
                    .filter(employee -> departmentName.equals(employee.getDepartmentName()))
                    .count();
            map.put("value", count);
            list.add(map);
        }

        return Result.success(list);
    }

}
